<!-- 安全标签 -->
<template>
  <el-card class="app-container">
    <div>
      <div class="itemTitle">安全标签</div>
      <div class="search">
        <el-form :inline="true" :model="queryParams" ref="queryForm">
          <el-col :span="5">
            <el-form-item label="标签名称" prop="name">
              <el-input
                v-model="queryParams.name"
                placeholder="请输入名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item>
              <el-button type="primary" @click="handleQuery">搜索</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </div>
      <div class="content">
        <div class="ct-btns">
          <el-button
            type="primary"
            @click="handleAdd"
            v-hasPermi="['base:label:add']"
            >新增</el-button
          >
        </div>
        <div class="ct-table">
          <elTables
            :currentPage="queryParams.pageNum"
            :table-data="tableData"
            :columns="tableColumns"
            :totalLength="total"
            :handle-current-change="handleCurrentChange"
            isPagin
            :curHeight="tableHeight"
          />
        </div>
      </div>
    </div>
    <!-- 新增或修改安全标签对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      append-to-body
      @close="cancel"
      class="dialog-form"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-col :span="12">
          <el-form-item label="标签名称" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入名称"
              :readonly="!isEdit"
              :disabled="!isEdit"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规格" prop="spec">
            <el-input
              v-model="form.spec"
              placeholder="请输入规格"
              :readonly="!isEdit"
              :disabled="!isEdit"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="ramke">
            <el-input
              v-model="form.ramke"
              type="textarea"
              placeholder="请输入内容"
              :readonly="!isEdit"
              :disabled="!isEdit"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="图片标识" prop="file">
            <elUploads
              :readonly="!isEdit"
              :disabled="!isEdit"
              :ref="'upload'"
              :action="action"
              :auto-upload="true"
              :limit="limit"
              :fileList="fileList"
              :remove-file="removeFile"
              :accept="'.jpg,.png'"
              :success-fun="success"
              :before-upload="uploadBeforeUpload"
              tip="提示：仅允许上传.jpg,.png格式文件，且不能超过100M！"
            ></elUploads>
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
    <!-- 导入 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="800px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="upload.open = false">取消</el-button>
        <el-button type="primary" @click="submitFileForm">确定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
const defaultQueryParams = {
  pageNum: 1,
  pageSize: 10,
};
import { getToken } from "@/utils/auth";
import {
  pageLabel,
  getLabel,
  delLabel,
  addLabel,
  updateLabel,
} from "@/api/safetyManagement/certificate/safetyTag";

export default {
  name: "Label",
  data() {
    return {
      fileList: [],
      limit: 1,
      action: process.env.VUE_APP_BASE_API + "/common/upload",
      tableHeight: 0,
      isEdit: false,
      dialogFormVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/base/label/importData",
      },
      tableData: [],
      // 查询参数
      queryParams: {
        ...defaultQueryParams,

        name: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        spec: [{ required: true, message: "规格不能为空", trigger: "blur" }],
        file: [
          { required: true, message: "图片标识不能为空", trigger: "blur" },
        ],
      },
      tableColumns: [
        { key: "name", title: "标签名称" },
        {
          key: "file",
          title: "图片标识",
          render: (h, params) => {
            console.log('click',params);
            return h("div", [
              h("el-image", {
                props: {
                  src:
                    String(params.row.file).indexOf("http") > -1
                      ? params.row.file
                      : process.env.VUE_APP_BASE_API + params.row.file,
                  previewSrcList: [
                    String(params.row.file).indexOf("http") > -1
                      ? params.row.file
                      : process.env.VUE_APP_BASE_API + params.row.file,
                  ],
                },
                style: {
                  width: "142px",
                  height: "80px",
                  verticalAlign: "middle",
                },
              }),
            ]);
          },
        },
        { key: "spec", title: "规格" },
        { key: "updateTime", title: "更新日期" },
        { key: "ramke", title: "备注" },
        {
          title: "操作",
          align: "center",
          fixed: "right",
          width: 200,
          render: (h, params) => {
            return h("div", [
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["base:label:info"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleUpdate(params.row, 2);
                    },
                  },
                },
                "查看"
              ),
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["base:label:edit"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleUpdate(params.row, 1);
                    },
                  },
                },
                "编辑"
              ),
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["base:label:remove"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleDelete(params.row);
                    },
                  },
                },
                "删除"
              ),
            ]);
          },
        },
      ],
    };
  },
  created() {
    this.getPage();
  },
  mounted() {
    this.$nextTick(() => {
      this.getTableHeight();
    });
  },
  methods: {
    uploadBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 100;
      if (!isRightSize) {
        this.$message.error("文件大小超过 100MB");
      }
      return isRightSize;
    },
    removeFile() {
      this.form.file = []; // 置空url
      this.fileList = [];
    },
    // 上传文件
    success(response, file, fileList) {
      if (response.code == 200) {
        this.fileList = [];
        this.fileList.push(response.fileName);
        this.form.file = this.fileList.toString();
        this.$refs.form.clearValidate("file");
        this.$message.success("上传成功！");
      }
    },
    getTableHeight() {
      let height = document.getElementsByClassName("ct-table")[0].clientHeight;
      this.tableHeight = height - 40;
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getPage();
    },
    /** 查询安全标签列表 */
    getPage() {
      this.loading = true;
      pageLabel(this.queryParams).then((response) => {
        this.tableData = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.$refs.upload.$refs.uploadRef.clearFiles();
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        spec: null,
        file: null,
        ramke: null,
        factoryId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        createDept: null,
        delFlag: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getPage();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isEdit = true;
      this.title = "新增安全标签";
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      if (type == 1) {
        this.isEdit = true;
        this.title = "编辑安全标签";
      } else {
        this.isEdit = false;
        this.title = "查看安全标签";
      }
      this.reset();
      const id = row.id || this.ids;
      getLabel(id).then((response) => {
        this.form = response.data;
        console.log('this.form',this.form);      
        this.open = true;
        this.fileList = [{ name: response.data.name, url: response.data.file }];
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateLabel(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.$refs.upload.$refs.uploadRef.clearFiles();
              this.open = false;
              this.getPage();
            });
          } else {
            addLabel(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.$refs.upload.$refs.uploadRef.clearFiles();
              this.open = false;
              this.getPage();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          let data;
          if (Array.isArray(ids)) {
            data = ids;
          } else {
            data = [ids];
          }
          return delLabel(data);
        })
        .then(() => {
          this.getPage();
          this.msgSuccess("删除成功");
        });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getPage();
    },
    // 提交导入文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
<style lang="scss" scoped></style>
